import * as React from "react";
import { Component } from "react";
import {
  Table,
  Input,
  Select,
  Button,
  Modal,
  message,
  Space,
  Tabs,
  DatePicker,
} from "antd";
import {
  getDeviceManagement,
  getComponentType,
  getembarkation,
  getDaysfreezing,
  getdeviceread,
  getunloaddevice,
  getmeterreading,
  remoteControl,
} from "../deviceseversapi";
import "./index.less";
import Consequence from "../ResultsQuery/compontents/Consequence";
import { AjaxData } from "../../../../data/interface/publicInterface";
import { WebVariable } from "../../../../data/WebVariable";
const DatePickers:any= DatePicker;
const { TabPane } = Tabs;
//

export interface ScreenProps {}
const { Option } = Select;

export interface ScreenState {
  type: Number;
  time: "date" | "time" | "month" | "year" | "week" | "quarter";
  loading: boolean;
  selectedRowKeys: number[];
  terminalselectedRowKeys: number[];
  terminaldatalist: number[];
  terminaltotal: number;
  terminalpage: number;
  terminalsize: number;
  terminalname: string;
  visible: boolean;
  binding: boolean;
  freeze: boolean;
  datalist: number[];
  status: number;
  id: number[];
  freezingtime: string;
  ternimalInfo: string;
  deviceInfo: string;
  deviceTypeId: string;
  energyType: string;
  isLoad: string;
  addtitle: string;
  batch: string;
  condition: string;
  selectedRows: rowDataType[];
  addedit: number;
  protocollist: number[];
  page: number;
  size: number;
  total: number;
  batchbinding: boolean;
  boundstate: number;
  typeId: string;
  bound: boolean;
  agreementlist: number[];
  controlVisible: boolean;
  controlItem: any[];
  controlValue: string;
}
export enum dateEnum {
  "date" = "date",
  "time" = "time",
  "month" = "month",
  "year" = "year",
}
interface rowDataType {
  terminalId: string;
  id: string;
  name: string;
  energyType: string;
  isLoad: string;
}

interface provinceClass {
  name: string;
  id: number;
}

class DeviceDebugging extends Component<ScreenProps, ScreenState> {
  state = {
    type: 1,
    time: dateEnum.date,
    selectedRowKeys: [], // Check here to configure the default column
    terminalselectedRowKeys: [],
    loading: false,
    isModalVisible: false,
    visible: false,
    binding: false,
    addtitle: "新增",
    batch: "删除终端设备信息",
    terminallist: {},
    terminaldatalist: [],
    terminaltotal: 0,
    terminalpage: 1,
    terminalsize: 5,
    terminalname: "",
    id: [],
    freezingtime: "", //抄表日冻结日期
    datalist: [],
    status: 1, //1就是删除 2是解绑 3是绑定
    deviceInfo: "",
    ternimalInfo: "",
    deviceTypeId: "",
    energyType: "",
    isLoad: "",
    condition: "", //新增协议默认内容  编辑协议文本
    freeze: false, //ridongjieridongjie
    protocollist: [],
    page: 1,
    size: 10,
    total: 0,
    addedit: 1, //1新增或者2编辑
    batchbinding: false, //批量绑定弹窗条件
    boundstate: 1, //1为批量绑定 2为单个绑定 分别控制不同弹窗
    typeId: "", //获取绑定协议id
    agreementlist: [], //获取协议的列表
    bound: false, //单个绑定
    selectedRows: [], //表格选中单行数据
    controlVisible: false,
    controlItem: [
      { text: "开阀", val: "55" },
      { text: "半开", val: "77" },
      { text: "关阀", val: "99" },
    ],
    controlValue: "", //阀控命令值
  };

  private columns = [
    {
      key: "isLoad",
      title: "装载",
      dataIndex: "isLoad",
      width: 80,
      render: (text, record, index) => {
        let isLoad = "";
        if (record.isLoad === "1") {
          isLoad = '<span class="are_loading">是</span>';
        } else {
          isLoad = '<span class="no_loading">否</span>';
        }
        return <div dangerouslySetInnerHTML={{ __html: isLoad }} />;
      },
    },
    {
      key: "name",
      title: "设备名称",
      dataIndex: "name",
      width: 200,
    },
    {
      key: "devAddr",
      title: "设备地址",
      dataIndex: "devAddr",
      width: 100,
    },
    {
      key: "energyType",
      title: "能源类型",
      dataIndex: "energyType",
      width: 80,
      render: (text, record, index) => {
        let txtVal = "";
        if (record.energyType === "1") {
          txtVal = "电";
        } else if (record.energyType === "2") {
          txtVal = "水";
        } else if (record.energyType === "3") {
          txtVal = "原煤";
        } else if (record.energyType === "4") {
          txtVal = "原油";
        } else if (record.energyType === "5") {
          txtVal = "天然气";
        } else if (record.energyType === "6") {
          txtVal = "蒸气";
        } else {
          txtVal = "";
        }
        return txtVal;
      },
    },
    {
      key: "typeName",
      title: "分项类型",
      dataIndex: "typeName",
      width: 100,
    },
    {
      key: "terName",
      title: "终端名称",
      dataIndex: "terName",
      width: 100,
    },
    {
      key: "terAddress",
      title: "终端地址",
      dataIndex: "terAddress",
      width: 100,
    },

    {
      key: "cldh",
      title: "测量点",
      dataIndex: "cldh",
      width: 80,
    },
  ];
  componentDidMount() {
    this.fetchget();
    this.agreement();
  }
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys: selectedRowKeys,
      selectedRows: selectedRows,
    });
  };

  render() {
    const controlHandleCancel = () => {
      this.setState({
        controlVisible: false,
      });
    };

    //阀控选择命令后确定操作
    const controlHandleOk = () => {
      let that = this;
      if (this.state.controlValue === "") {
        message.info("请选择控制命令");
        return;
      }
      let item: any = this.state.selectedRows[0];
      let data = {
        operateCode: this.state.controlValue,
        files: this.state.selectedRowKeys,
        terminalId: item.terminalId,
      };
      remoteControl(data)
        .then((res) => {
          if (res) {
            let Json: any = res;
            if (Json.code === 200) {
              that.setState({
                controlVisible: false,
              });
              message.info("阀控命令已下发，请查看执行结果!");
            } else {
              message.error(Json.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    const freezehandleCancel = () => {
      this.setState({
        controlVisible: false,
      });
    };
    //日冻结选择日期后确定操作
    const freezehandleOk = () => {
      let that = this;
      if (this.state.freezingtime === "") {
        message.info("请青选择时间");
        return;
      }
      let terid: any = this.state.selectedRows[0];
      let data = {
        commandKey: "daily_freeze",
        dateStr: this.state.freezingtime,
        files: this.state.selectedRowKeys,
        terminalId: terid.terminalId,
      };
      getDaysfreezing(data)
        .then((res) => {
          if (res) {
            let Json: any = res;
            if (Json.code === 200) {
              that.setState({
                freeze: false,
              });
              message.info("日冻结抄读命令已下发，请查看执行结果!");
            } else {
              message.error(Json.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //远程阀控
    const controlShowModal = () => {
      if (!validateIsLoadDevice()) {
        return;
      }
      let item: any = this.state.selectedRows[0];
      if (item.energyType === "1") {
        this.setState({
          controlItem: [
            { text: "跳闸", val: "1A" },
            { text: "合闸允许", val: "1B" },
            { text: "直接合闸", val: "1C" },
            { text: "报警", val: "2A" },
            { text: "报警解除", val: "2B" },
            { text: "保电", val: "3A" },
            { text: "保电解除", val: "3B" },
          ],
        });
      }
      this.setState({
        controlVisible: true,
      });
    };
    //抄读日冻结
    const freezeshowModal = () => {
      if (!validateIsLoadDevice()) {
        return;
      }

      this.setState({
        freeze: true,
      });
    };
    //抄读当前表码
    const meterreadingshowModal = () => {
      if (!validateIsLoadDevice()) {
        return;
      }
      let firstRecord: rowDataType = this.state.selectedRows[0];

      let data = {
        commandKey: "current_readout",
        files: this.state.selectedRowKeys,
        terminalId: firstRecord.terminalId,
      };
      getmeterreading(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("当前表码抄读命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    //卸载操作
    const dischargeshowModal = () => {
      if (!validateIsLoadDevice()) {
        return;
      }
      let firstRecord: rowDataType = this.state.selectedRows[0];
      let data = {
        files: this.state.selectedRowKeys,
        terminalId: firstRecord.terminalId,
      };

      getunloaddevice(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("卸载命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //装载操作
    const bindingshowModal = () => {
      if (this.state.selectedRowKeys.length === 0) {
        message.error("请选择已装载设备");
        return;
      }

      let temp = this.state.selectedRows.filter(
        (item: rowDataType) => item.isLoad === "1"
      );
      if (temp.length > 0) {
        message.error("选择中存在已装载设备，不能装载！");
        return;
      }

      if (this.state.selectedRowKeys.length > 10) {
        message.error("一次操作不大于10个设备！");
        return;
      }
      //终端ID数组
      let termArrayAll: string[] = [];
      this.state.selectedRows.forEach((item: rowDataType) => {
        if (item.terminalId) {
          termArrayAll.push(item.terminalId);
        }
      });
      let termArray = termArrayAll.filter(
        (x, index, self) => self.indexOf(x) === index
      );
      if (termArray.length > 1) {
        //存在多个终端
        message.error("一次只能操作一个终端的设备！");
        return;
      }

      let firstRecord: rowDataType = this.state.selectedRows[0];
      let data = {
        files: this.state.selectedRowKeys,
        terminalId: firstRecord.terminalId,
      };
      getembarkation(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("装载命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    //读取操作
    const readshowModal = () => {
      if (!validateIsLoadDevice()) {
        return;
      }
      let firstRecord: rowDataType = this.state.selectedRows[0];
      let data = {
        files: this.state.selectedRowKeys,
        terminalId: firstRecord.terminalId,
      };
      getdeviceread(data)
        .then((res: any) => {
          if (res) {
            if (res.code === 200) {
              message.info("读取命令已下发，请查看执行结果!");
            } else {
              message.error(res.message);
            }
          } else {
            message.info("失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    //已装载设备验证
    const validateIsLoadDevice = () => {
      if (this.state.selectedRowKeys.length === 0) {
        message.info("请选择已装载设备");
        return false;
      }
      let temp = this.state.selectedRows.filter(
        (item: rowDataType) => item.isLoad === "0"
      );
      if (temp.length > 0) {
        message.error("选项中存在档案未装载设备！");
        return false;
      }
      //终端ID数组
      let termArrayAll: string[] = [];
      this.state.selectedRows.forEach((item: rowDataType) => {
        if (item.terminalId) {
          termArrayAll.push(item.terminalId);
        }
      });
      let termArray = termArrayAll.filter(
        (x, index, self) => self.indexOf(x) === index
      );
      if (termArray.length > 1) {
        //存在多个终端
        message.error("一次只能操作一个终端的设备！");
        return false;
      }
      if (selectedRowKeys.length > 10) {
        message.error("一次操作不大于10个设备！");
        return false;
      }
      return true;
    };

    // 表格复选
    const selectedRowKeys = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    //表格复选框
    let that = this;
    let pagination = {
      total: this.state.total,
      defaultCurrent: this.state.page,
      pageSize: this.state.size,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {},
      onChange: (current, pageSize) => {
        that.setState(
          {
            page: current,
          },
          () => {
            this.fetchget();
          }
        );
      },
    };

    return (
      <>
        <div className="DeviceDebugging">
          <Tabs defaultActiveKey="1">
            <TabPane tab="设备调试" key="1">
              <div className="rowcon_body">
                <div className="querystat">
                  设备：
                  <Input
                    className="input"
                    placeholder="设备名称或地址"
                    value={this.state.deviceInfo}
                    onChange={(event) => {
                      this.deviceChange(event);
                    }}
                  />
                </div>
                <div className="query">
                  终端：
                  <Input
                    className="input"
                    placeholder="终端名称或地址"
                    value={this.state.ternimalInfo}
                    onChange={(event) => {
                      this.terminalChange(event);
                    }}
                  />
                </div>
                <div className="query">
                  分项类型：
                  <Select
                    defaultValue={this.state.deviceTypeId}
                    className="searchselect"
                    onChange={(event) => {
                      this.onSecondCityChange(event);
                    }}
                  >
                    {this.state.protocollist.map((province: provinceClass) => (
                      <Option key={province.id} value={province.id}>
                        {province.name}
                      </Option>
                    ))}
                  </Select>
                </div>
                <div className="query">
                  装载类型：
                  <Select
                    defaultValue={this.state.isLoad}
                    className="searchselect"
                    onChange={(event) => {
                      this.isLoadChange(event);
                    }}
                  >
                    <Option value="0">未装载</Option>
                    <Option value="1">已装载</Option>
                  </Select>
                </div>
                <div className="query">
                  能源类型：
                  <Select
                    defaultValue={this.state.energyType}
                    className="searchselect"
                    onChange={(event) => {
                      this.energyChange(event);
                    }}
                  >
                    {WebVariable.categoryType.map((item: any) => {
                      return (
                        <Option value={item.key} key={item.key}>
                          {item.label}
                        </Option>
                      );
                    })}
                  </Select>
                </div>
                <div className="query">
                  <Button
                    type="primary"
                    onClick={() => {
                      this.fetchget();
                    }}
                  >
                    查询
                  </Button>
                </div>
              </div>
              <div className="subject">
                <div className="operation">
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={bindingshowModal}
                  >
                    装载
                  </Button>
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={readshowModal}
                  >
                    读取
                  </Button>
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={dischargeshowModal}
                  >
                    卸载
                  </Button>
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={meterreadingshowModal}
                  >
                    抄读当前表码
                  </Button>
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={freezeshowModal}
                  >
                    抄读日冻结
                  </Button>
                  <Button
                    type="primary"
                    className="binding"
                    size="middle"
                    onClick={controlShowModal}
                  >
                    远程阀控
                  </Button>
                </div>
                <div>
                  <Table
                    style={{ paddingTop: 16 }}
                    rowSelection={rowSelection}
                    columns={this.columns}
                    dataSource={this.state.datalist}
                    pagination={pagination}
                  />
                </div>
              </div>
            </TabPane>
            <TabPane tab="结果查询" key="2">
              <Consequence />
            </TabPane>
          </Tabs>

          <Modal
            title="抄读日冻结"
            visible={this.state.freeze}
            onOk={freezehandleOk}
            onCancel={freezehandleCancel}
            maskClosable={false}
          >
            <div>
              <Space direction="vertical">
                <DatePickers
                  allowClear={false}
                  onChange={(event, data) => {
                    this.DaysfreezingChange(event, data);
                  }}
                />
              </Space>
            </div>
          </Modal>

          <Modal
            title="远程控制"
            visible={this.state.controlVisible}
            onOk={controlHandleOk}
            onCancel={controlHandleCancel}
            maskClosable={false}
          >
            <div>
              <Space direction="vertical">
                <Select
                  placeholder="请选择命令"
                  style={{ width: "100px" }}
                  onChange={(event) => {
                    this.controlChange(event);
                  }}
                >
                  {this.state.controlItem.map((item: any) => (
                    <Option key={item.val + ""} value={item.val + ""}>
                      {item.text}
                    </Option>
                  ))}
                </Select>
              </Space>
            </div>
          </Modal>
        </div>
      </>
    );
  }
  //读取数据
  async fetchget() {
    let data = {
      pageIndex: this.state.page,
      pageSize: this.state.size,
      queryData: {
        devVal: this.state.deviceInfo,
        energyType: this.state.energyType,
        isBing: "1",
        isFictitious: "0",
        isLoad: this.state.isLoad,
        terVal: this.state.ternimalInfo,
        typeId: this.state.deviceTypeId,
      },
    };

    let res: any = await getDeviceManagement(data).catch((err) => {
      console.log(err);
    });
    const json: AjaxData = res;
    if (json.success) {
      let date = json.data.records;
      for (let i in date) {
        let key = "key";
        let value = date[i].id;
        date[i][key] = value;
      }
      this.setState({
        datalist: date,
        total: json.data.total,
      });
    }
  }
  //获取终端查询条件
  terminalChange(e) {
    this.setState({
      ternimalInfo: e.target.value,
    });
  }
  //获取设备查询条件
  deviceChange(e) {
    this.setState({
      deviceInfo: e.target.value,
    });
  }
  //是否装载
  isLoadChange(e) {
    let inputValue = e;
    this.setState({
      isLoad: inputValue,
    });
  }
  //能源选项
  energyChange = (value) => {
    let inputValue = value;

    this.setState({
      energyType: inputValue,
    });
  };
  //分项类型选择
  onSecondCityChange = (value) => {
    let inputValue = value;
    this.setState({
      deviceTypeId: inputValue,
    });
  };
  //日冻结日期选贼
  DaysfreezingChange = (date, dateString) => {
    let inputValue = dateString;

    this.setState({
      freezingtime: inputValue,
    });
  };
  //获取分项类型下拉
  async agreement() {
    let res: any = await getComponentType().catch((err) => {
      console.log(err);
    });
    const json: any = res;
    if (res) {
      this.setState({
        protocollist: json.data,
      });
    }
  }
  //命令选项
  controlChange = (value) => {
    let inputValue = value;

    this.setState({
      controlValue: inputValue,
    });
  };
}

export default DeviceDebugging;
